
$.datepicker.regional['zh-CN'] = {
    clearText: '清除',
    clearStatus: '清除已选日期',
    closeText: '关闭',
    closeStatus: '不改变当前选择',
    prevText: '<上月',
    prevStatus: '显示上月',
    prevBigText: '<<',
    prevBigStatus: '显示上一年',
    nextText: '下月>',
    nextStatus: '显示下月',
    nextBigText: '>>',
    nextBigStatus: '显示下一年',
    currentText: '今天',
    currentStatus: '显示本月',
    monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
    monthNamesShort: ['一','二','三','四','五','六', '七','八','九','十','十一','十二'],
    monthStatus: '选择月份',
    yearStatus: '选择年份',
    weekHeader: '周',
    weekStatus: '年内周次',
    dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
    dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
    dayNamesMin: ['日','一','二','三','四','五','六'],
    dayStatus: '设置 DD 为一周起始',
    dateStatus: '选择 m月 d日, DD',
    dateFormat: 'yy-mm-dd',
    firstDay: 1,
    initStatus: '请选择日期',
    isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['zh-CN']);


$(function () {
    $.validator.addMethod("specialCharValidate", function(value, element) {
        var pattern = new RegExp("[`!%#$^&*=()|{}'\\[\\]<>?\\%……+￥‘'\"]");
        return this.optional(element)||!pattern.test(value) ;
    }, $.validator.format($.validator.messages["specialCharValidate"]));

    $.validator.addMethod("chinaMobileValidate", function(value, element) {
    	 var pattern = new RegExp("(13[4-9]\\d{8}|15\\d{9}|147\\d{8}|183\\d{8}|182\\d{8}|188\\d{8}|187\\d{8}|17\\d{9})");
        return this.optional(element)||!pattern.test(value) ;
    }, $.validator.format($.validator.messages["chinaMobileValidate"]));
    $.validator.addMethod("intValidate", function(value, element) {
        var pattern = new RegExp("[\\d*]");
        return this.optional(element)||!pattern.test(value) ;
    }, $.validator.format($.validator.messages["intValidate"]));

    $.validator.addMethod("hanWordValidate", function(value, element) {
        var pattern = new RegExp("[\x00-\xff]");
        return this.optional(element)||!pattern.test(value) ;
    }, $.validator.format($.validator.messages["hanWordValidate"]));

    $.validator.addMethod("hanWordLenValidate", function(value, element, params) {
        var result = value.replace(/[^\x00-\xff]/g, '**').length > params[0];
        return this.optional(element) || !result;
    }, $.validator.format($.validator.messages["hanWordLenValidate"]));
});

(function ($) {
    String.format = function() {
        if (arguments.length == 0)
            return null;
        var str = arguments[0];
        for ( var i = 1; i < arguments.length; i++) {
            var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
            str = str.replace(re, arguments[i]);
        }
        return str;
    };

    $.fn.wordLeftTip = function(options) {
        var settings = $.extend({
            renderTo: '',
            maxLength: 100,
            alert: false,
            alertTip: '你的输入超出了{0}字',
            remainTip: '剩余字数: {0}字'
        }, options);
        return this.each(function() {
            var $this = $(this);
            var curr = String.format(settings.remainTip, settings.maxLength);
            if (settings.renderTo) {
                $(settings.renderTo).html(curr);
            }
            $this.bind('input propertychange', function(e) {
                e.preventDefault();
                if ($this.val().length > settings.maxLength) {
                    $this.val($this.val().substring(0, settings.maxLength));
                    if (settings.alert) {
                        alert(String.format(settings.alertTip, settings.maxLength));
                    }
                }
                //
                var curr = String.format(settings.remainTip, (settings.maxLength - $this.val().length));
                if (settings.renderTo) {
                    $(settings.renderTo).html(curr);
                }
            });
            // init val
            if (settings.renderTo) {
                var _curr = String.format(settings.remainTip, (settings.maxLength - $this.val().length));
                if (settings.renderTo) {
                    $(settings.renderTo).html(_curr);
                }
            }
        });
    };
    
    $.fn.uploadImg = function (options) {
        var defaults = $.extend({
            fileInputName: 'inputImageFile',
            maxSize: 2,
            allowSuffix: [".jpg", ".jpeg", ".png"]
        }, options);
        return this.each(function() {
            var $this = $(this);
            $('body').find('input[name="' + defaults.fileInputName + '"]').remove();
            var imgCtrl = $('<img class="img-upload-preview" src="" width="100%;"/>');
            var uploadBtn = $('<div><a href="javascript:void(0);" class="img-button-upload">+上传图片</a></div>');
            var inputPic = $('<input type="file" name="' + defaults.fileInputName + '" style="position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity:0);opacity: 0;width:260px">');
            $this.append(imgCtrl).append(uploadBtn).append(inputPic);
            $('.img-button-upload').on('click', function(e){
                if (typeof FileReader === 'undefined') {
                    alert('抱歉，你的浏览器不支持自定义附件上传');
                } else {
                    inputPic.on('change', function () {
                        var inputFile = this;
                        //检查文件类型和大小, 单位:M
                        var maxSize = defaults.maxSize;
                        var filepath = $(this).val();
                        var filesuffix = filepath.substring(filepath.lastIndexOf("."), filepath.length);
                        console.log(filesuffix);
                        if (defaults.allowSuffix && $.isArray(defaults.allowSuffix)) {
                            var isOk = false;
                            if (filesuffix) {
                                for ( var i = 0; i < defaults.allowSuffix.length; i++) {
                                    if (defaults.allowSuffix[i].toLowerCase() == filesuffix.toLowerCase()) {
                                        isOk = true;
                                    }
                                }
                            }
                            if (!isOk) {
                                inputPic.val('');
                                alert("图片类型不支持, 请重新选择图片");
                                return;
                            }
                        }
                        var fileSize = 0;
                        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
                        if (isIE && !inputPic[0]) {
                            var filePath = inputPic.val();
                            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
                            if (fileSystem.FileExists(filePath)) {
                                var file = fileSystem.GetFile(filePath);
                                fileSize = file.Size;
                            }
                        } else {
                            fileSize = inputPic[0].size;
                        }
                        var size = fileSize / 1024;
                        if (size > maxSize) {
                            alert("附件大小不能大于" + maxSize / (1024 * 1024)+ "M");
                            return;
                        }
                        if (inputFile.files && inputFile.files[0]) {
                            var reader = new FileReader();
                            reader.onload = function (e) {
                                $('.img-upload-preview').attr('src', e.target.result);
                            };
                            reader.readAsDataURL(this.files[0]);
                        }
                    });
                    inputPic.focus().click();
                }
            });
        });
    };

    $.fn.validator = function (options) {
        var defaults = $.extend({
            url: '',
            hasUpload: false,
            validatorItems: {},
            submit: function (form) {}
        }, options);
        var errorMsg = {
            required: '此字段为必填字段',
            specialCharValidate: '此字段不允许输入特殊字符',
            email: "此字段不符合EMAIL格式要求",
            number: "此字段必须输入数字",
            equalTo: "此字段必须为指定值",
            maxlength: $.validator.format( "此字段最大不能超过{0}个字符" ),
            minlength: $.validator.format( "此字段最小不能少于{0}个字符" ),
            date: "此字段不符合日期格式[yyyy-mm-dd]",
            chinaMobileValidate: "此字段要求输入中国移动手机号",
            hanWordValidate: "此字段只能输入汉字",
            hanWordLenValidate: "此字段只能输入{0}个汉字"
        };
        return this.each(function() {
            var $this = $(this);
            var rules = {},
                messages = {};
            for (var key in defaults.validatorItems) {
                var rule = {};
                var msg = {};
                var validatorItem = defaults.validatorItems[key];
                for (var i=0; i<validatorItem.length; i++) {
                    var _validItem = validatorItem[i];
                    if (_validItem.indexOf(':') > 0) {
                        rule[_validItem.substr(0, _validItem.indexOf(':'))] = _validItem.substr(_validItem.indexOf(':') + 1, _validItem.length);
                    } else {
                        rule[validatorItem[i]] = true;
                    }
                    msg[validatorItem[i]] = errorMsg[validatorItem[i]];
                }
                rules[key] = rule;
                messages[key] = msg;
            }
            $this.validate({
                rules: rules,
                messages: messages,
                submitHandler: function(form) {
                    $form = $(form);
                    if (defaults.ajaxSubmit && $.isFunction(defaults.ajaxSubmit)) {
                        defaults.ajaxSubmit(defaults.url, $form.serialize());
                    } else {
                        if (!$form.attr('action')) {
                            $form.attr('action', defaults.url);
                        }
                        if (!$form.attr('post')) {
                            $form.attr('method', 'post');
                        }
                        if (defaults.hasUpload && !$form.attr('enctype')) {
                            $form.attr('enctype', 'multipart/form-data');
                        }
                        form.submit();
                    }
                },
                onfocusout: function (){
                    return false;
                },
                highlight: function(element, errorClass) {
                    $(element).fadeOut(function() {
                        $(element).fadeIn();
                    });
                },
                invalidHandler : function(){
                    return false;
                },
                showErrors: function(errorMap, errorList) {
                    $('.error-star').remove();
                    for (var i=0; i<errorList.length; i++) {
                        var element = $(errorList[i].element);
                        var errorMsg = errorList[i].message;
                        if (!$(element).next().hasClass('error-star')) {
                            $('<span class="error-star" style="color: red;" title="' + errorMsg + '">(×)</span>').insertAfter(element);
                        }
                    }
                }
            });

        });
    };

    $.fn.rowAccordion = function (options) {
        var defaults = $.extend({
            url: '',
            hasUpload: false,
            validatorItems: {},
            submit: function (form) {}
        }, options);
        return this.each(function() {
            var $this = $(this);
            $('.accordion-content').hide();
            $('.accordion-title').addClass("accordion-close");
            $this.find('input[type=checkbox]').on('click', function (e) {
                var self = $(this);
                var _titlePanel = self.parent().next().children().first();
                var _contentPanel = self.parent().next().children().last();
                if (self.prop("checked")) {
                    _contentPanel.slideDown("fast");
                    _titlePanel.removeClass('accordion-close');
                    _titlePanel.addClass('accordion-open')
                } else {
                    _contentPanel.slideUp("fast");
                    _titlePanel.removeClass('accordion-open');
                    _titlePanel.addClass('accordion-close')
                }
            });
            $this.find('.accordion-title').on('click', function (e) {
                var self = $(this);
                var _contentPanel = self.next();
                if (self.hasClass('accordion-close')) {
                    _contentPanel.slideDown("fast");
                    self.removeClass('accordion-close');
                    self.addClass('accordion-open')
                } else {
                    _contentPanel.slideUp("fast");
                    self.removeClass('accordion-open');
                    self.addClass('accordion-close')
                }
            });
        });
    };
})(jQuery);